﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Quexcel.OpenXML.Excel;

namespace Quexcel.OpenXML.Utils
{
    internal static class Util
    {
        public static Regex CellAddressPattern
            = new Regex("\\$?(?<cell>[^\\d])\\$?(?<row>\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        public static Regex RangeAddressPattern
            = new Regex("(?<sheet>\\w+)!\\$?(?<startCell>\\w+)\\$?(?<startRow>\\d+):\\$?(?<endCell>\\w+)\\$?(?<endRow>\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        public static string AddCellAdress(string cellAddress, int numberOfCells, int numberOfRows)
        {
            string[] address = CellAddressPattern.Match(cellAddress).Result("${cell}:${row}").Split(':');
            int row = Convert.ToInt32(address[1]);

            row += numberOfRows;
            if (numberOfCells > 0)
            {
                int cell = CellAddressToNumber(address[0]);
                cell += numberOfCells;
                return CellNumberToAddress(cell) + row;
            }
            return address[0] + row;
        }

        public static string CellNumberToAddress(int number)
        {
            if (number > 0)
            {
                int higherOrderNumber = (int)number / 26;
                return CellNumberToAddress(higherOrderNumber) + (char)(number - higherOrderNumber * 26 + (int)'A' - 1);
            }
            else
                return "";
        }

        public static int CellAddressToNumber(string address)
        {
            int number = 0;
            for (int i = 0; i < address.Length; i++)
            {
                number += ((int)address[address.Length - 1 - i] - (int)'A' + 1) * (i + 1);
            }
            return number;
        }

        public static Address GetAddress(string address)
        {
            Address a = new Address();
            string[] output = CellAddressPattern.Match(address).Result("${cell}:${row}").Split(':');
            a.row = Convert.ToInt32(output[1]);
            a.cell = output[0];

            return a;
        }
    }
}
